<template>
    <div style="padding: 20px;">
        <div style="font-size: 16px;font-weight: 700;height: 32px;">用户信息</div>
        <div style="font-size: 12px;flood-color: #999;"></div>
        <div>
            <div style="font-size: 14px;font-weight: 400;color: #606266;height: 80px;line-height: 80px;"><el-avatar :size="80" :src="user.avatar"></el-avatar></div>
            <div class="user-info-item">用户名：{{ user.username }} </div>
            <div class="user-info-item">昵称：{{ user.nickname }}</div>
            <div class="user-info-item">性别：{{ user.genderName }}</div>
            
            <div class="user-info-item">
                <span>邮箱：{{ user.email }}</span>
                <el-button type="text" style="margin-left: 10px;" @click="openDialog('email')">换绑</el-button>
            </div>
            <div class="user-info-item">
               <span>手机号码：{{ user.phone }}</span> 
               <el-button type="text" style="margin-left: 10px;" @click="openDialog('phone')">换绑</el-button>
            </div>
            <div class="user-info-item">注册时间：{{ user.regTime }}</div>
            
        </div>
        <div style="display: flex;justify-content: center;margin-top: 20px;">
            <i-button  level="info" @click.native="drawer.flag = true">修改个人资料</i-button>
            <i-button style="margin-left: 10px;" @click.native="logout">退出登录</i-button>
           
        </div>
        <el-drawer
        title="修改个人资料"
        :visible.sync="drawer.flag"
        size="35%"
        @open="openHandler"
        @close="$refs['userRef'].clearValidate();"
        >
            <div class="drawer-main">
                <el-form :model="drawer.info" ref="userRef" :rules="userRules" label-width="80px">
                    <el-form-item label="头像" prop="avatar">
                        <el-upload
                        class="avatar-uploader"
                        :action="upload.url"
                        :show-file-list="false"
                        :headers="upload.headers"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                            <img v-if="drawer.info.avatar" :src="drawer.info.avatar" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                        <div style="font-size: 12px;color: #999;">头像不能大于2MB</div>
                    </el-form-item>
                    <el-form-item label="昵称" prop="nickname">
                        <el-input v-model="drawer.info.nickname" placeholder="请输入昵称" />
                    </el-form-item>
                    <el-form-item label="性别" prop="gender">
                        <el-select v-model="drawer.info.gender">
                            <el-option :label="item.name" :value="parseInt(item.value)" v-for="(item,index) in genderList" :key="index" />
                        </el-select>
                    </el-form-item>
                </el-form>

                <div class="drawer-btn">
                    <i-button level="info" style="margin-right: 10px;" @click.native="updateUserInfo">确认修改</i-button>
                    <i-button @click.native="drawer.flag = false">取消</i-button>
                </div>
            </div>
        </el-drawer>
        <el-dialog
        :title="dialog.title"
        :visible.sync="dialog.flag"
        width="30%"
        @open="dialogOPenHandler"
        @close="$refs['bindingRef'].clearValidate();"
        :close-on-click-modal="false"
        >
            <div>
               <el-form :model="dialog.info" :rules="bandingRules" ref="bindingRef">
                    <el-form-item v-if="dialog.type === 'phone'">
                        <div>请输入{{ dialog.info.phone }} 完整的手机号码</div>
                    </el-form-item>
                    <el-form-item v-if="dialog.type === 'phone'" prop="oldPhone">
                        <el-input type="text" v-model="dialog.info.oldPhone" placeholder="输入完整的手机号码"></el-input>
                    </el-form-item>
                    <el-form-item v-if="dialog.type === 'phone'" prop="newPhone">
                        <el-input type="text" v-model="dialog.info.newPhone" placeholder="输入新的手机号码"></el-input>
                    </el-form-item>
                    <el-form-item v-if="dialog.type === 'email'">
                        <div>请输入{{ dialog.info.email }} 完整的邮箱</div>
                    </el-form-item>
                    <el-form-item v-if="dialog.type === 'email'" prop="oldEmail">
                        <el-input type="text" v-model="dialog.info.oldEmail" placeholder="输入完整的邮箱"></el-input>
                    </el-form-item>
                    <el-form-item v-if="dialog.type === 'email'" prop="newEmail">
                        <el-input type="text" v-model="dialog.info.newEmail" placeholder="输入新的邮箱"></el-input>
                    </el-form-item>
               </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <i-button @click.native="dialog.flag = false" style="margin-right: 10px;">取消</i-button>
                <i-button level="info" v-if="dialog.type === 'email'" @click.native="changeEmail">确定</i-button>
                <i-button level="info" v-if="dialog.type === 'phone'" @click.native="changePhone">确定</i-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import IButton from '@/components/plugs/i-button/IButton.vue'
import {get,post} from '@/utils/api.js'
import { rules } from '@/utils/rules'

export default {

    data(){

        let checkOldEmail = (rule, value, callback)=>{
            if(!rules.email.test(value)){
                return callback(new Error('邮箱格式不正确'));
            }

            return callback();
        }

        let checkNewEmail = (rule, value, callback)=>{
            if(!rules.email.test(value)){
                return callback(new Error('邮箱格式不正确'));
            }

            return callback();

        }

        let checkOldPhone = (rule, value, callback)=>{
            if(!rules.phone.test(value)){
                return callback(new Error('手机号格式不正确'));
            }

            return callback();

        }

        let checkNwePhone = (rule, value, callback)=>{
            if(!rules.phone.test(value)){
                return callback(new Error('手机号格式不正确'));
            }

            return callback();

        }

        return{
            upload:{
                url:'https://api.sns.qugeek.com/base-file/file/upload',
                headers:{}
            },
            dialog:{
                flag:false,
                title:'',
                type:'phone',
                info:{}
            },
            genderList:[],
            drawer:{
                flag:false,
                info:{}
            },
            user:{},
            userRules:{
                nickname:[{ required: true, message: '昵称不能为空', trigger: 'blur' }],
                gender:[{ required: true, message: '性别不能为空', trigger: 'blur' }]
            },
            bandingRules:{
                oldPhone:[{ required: true, message: '原本的手机号码不能为空', trigger: 'blur' },{validator:checkOldPhone,trigger:'blur'}],
                newPhone:[{ required: true, message: '新的手机号码不能为空', trigger: 'blur' },{validator:checkNwePhone,trigger:'blur'}],
                oldEmail:[{ required: true, message: '原本的邮箱不能为空', trigger: 'blur' },{validator:checkOldEmail,trigger:'blur'}],
                newEmail:[{ required: true, message: '新的邮箱不能为空', trigger: 'blur' },{validator:checkNewEmail,trigger:'blur'}]
            }

        }
    },
    methods:{
        getGenderList(){
            const promise = get({
                url:'/base-system/dict/load-by-code',
                params:{
                    code:'user_gender'
                }
            },false);

            promise.then(res=>{
                if(res.code === 200){
                    this.genderList = res.data.childNode;
                }
            })
        },
        getUserInfo(){
            const promise = get({
                url:'/base-user/front/user/details'
            });

            promise.then(res=>{
                if(res&&res.code === 200){
                    this.user = res.data;
                }
            })
        },
        updateUserInfo(){

            this.$refs['userRef'].validate(valid=>{

                if(valid){
                    const promise = post({
                        url:'/base-user/front/user/update',
                        data:{avatar:this.drawer.info.avatar,nickname:this.drawer.info.nickname,gender:this.drawer.info.gender}
                    });

                    promise.then(res=>{
                        if(res){
                            if(res.code === 200){
                                this.getUserInfo();
                                this.$message.success(res.message);
                                this.drawer.flag = false;
                                return;
                            }
                            this.$message.error(res.message);
                        }
                    })

                }else{
                    this.$message.error('表单数据校验不通过，请检查后重试~')
                }

            });

        },
        changePhone(){
            this.$refs['bindingRef'].validate(valid=>{
                if(valid){

                    const promise = post({
                        url:'/base-user/front/user/binding/phone',
                       data:{oldPhone:this.dialog.info.oldPhone,newPhone:this.dialog.info.newPhone}
                    });
                    promise.then(res=>{
                        if(res){
                            if(res.code === 200){
                                this.getUserInfo();
                                this.$message.success(res.message);
                                this.dialog.flag = false;
                                return;
                            }
                            this.$message.error(res.message);
                        }
                    })

                }else{
                    this.$message.error('表单数据校验不通过，请检查后重试~')
                }
            });

        },
        changeEmail(){
            this.$refs['bindingRef'].validate(valid=>{
                if(valid){

                    const promise = post({
                        url:'/base-user/front/user/binding/email',
                        data:{newEmail:this.dialog.info.newEmail,oldEmail:this.dialog.info.oldEmail}
                    });
                    promise.then(res=>{
                        if(res){
                            if(res.code === 200){
                                this.getUserInfo();
                                this.$message.success(res.message);
                                this.dialog.flag = false;
                                return;
                            }
                            this.$message.error(res.message);
                        }
                    })

                }else{
                    this.$message.error('表单数据校验不通过，请检查后重试~')
                }
            });
        },
        openHandler(){
            this.getGenderList();
            this.drawer.info = JSON.parse(JSON.stringify(this.user));
        },
        handleAvatarSuccess(res, file) {
            console.log('file',file);
            this.drawer.info.avatar = file.response.data.link;
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        openDialog(type){
            this.dialog.flag = true;
            this.dialog.type = type;
            if(type === 'phone'){
                this.dialog.title = '变更绑定手机号码'
            }else{
                this.dialog.title = '变更绑定邮箱'
            }
        },
        dialogOPenHandler(){
            this.dialog.info = JSON.parse(JSON.stringify(this.user))
        },
        logout(){
            const promise = get({
                url:'/base-auth/oauth/logout'
            });
            //退出登录
            promise.then(res=>{

                if(res.code === 200){
                this.$message.success(res.message);
                sessionStorage.removeItem('token');
                this.$router.push('/login');
                return;
                }
            })
        }

    },
    created(){
        const token =  localStorage.getItem('token');
        this.upload.headers = {'Authorization':token};
        this.getUserInfo();
    },
    components:{
        IButton

    }

}
</script>

<style scoped>

.user-info-item{
    font-size: 14px;
    font-weight: 400;
    color: #606266;
    min-height: 40px;
    line-height: 40px;
}

.drawer-main{
    position: relative;
    padding: 20px;
}

.drawer-btn{
    display: flex;
    /* justify-content: center; */
    position: fixed;
    bottom: 0;
    padding-bottom: 20px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .dialog-footer{
    display: flex;
    justify-content: flex-end;
  }

</style>